package com.netty.esc.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

/**
 * @ClassName: 11094
 * @Description:
 * @Author: Fisher
 * @Date: 2022/6/12 20:46
 **/
public class AlarmUtil {

    /**
     * 微信告警
     * */
    public static void alarm(String error){
        JSONObject json = new JSONObject();
        json.put("msg",error);
        doPostJson("http://82.157.6.212:8995/alarm/noticeFw",json);
    }


    /**
     * POST请求：携带JSON数据.
     *
     * @param url    请求地址
     * @param params 请求数据：JSON字符串
     * @return 响应数据
     */
    public static String doPostJson(String url, Object params) {
        try {
            // 创建客户端
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            // 建立连接
            HttpPost httpPost = new HttpPost(url);
            // 请求配置：超时时间，单位：毫秒
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
            httpPost.setConfig(requestConfig);
            // 设置请求头：内容类型
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(params), "UTF-8");
            httpPost.setEntity(stringEntity);
            return postResponse(httpClientBuilder, httpPost);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }


    /**
     * 获取POST请求数据.
     *
     * @param httpClientBuilder 客户端对象
     * @param httpPost          POST请求
     * @return 响应数据
     */
    public static String postResponse(HttpClientBuilder httpClientBuilder, HttpPost httpPost) {
        try (CloseableHttpResponse closeableHttpResponse = httpClientBuilder.build().execute(httpPost)) {
            HttpEntity httpEntity = closeableHttpResponse.getEntity();
            return EntityUtils.toString(httpEntity, "UTF-8");
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

}
